package com.bdqn.controller;

import com.bdqn.common.Constants;
import com.bdqn.pojo.StorageRecord;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.RecordService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@Controller
// @RestController // REST风格：所有方法不再返回视图名称，而是直接返回数据
public class StorageController {
    private RecordService recordService;
    private static final Logger logger = Logger.getLogger(StorageController.class);

    /**
     * 去到登录页
     */
    @GetMapping("/storageRecord/list")
    public String login() {
        return "storageRecord/list";
    }


    /**
     * 跳转到添加页面
     *
     * @param storageRecord 使用 @ModelAttribute("sysUser") 注解绑定对象数据到<fm:form method="post" modelAttribute="sysUser">表单
     */
    // @GetMapping("/add")
    public String toAdd(@ModelAttribute("storageRecord") StorageRecord storageRecord) {
        return "storageRecord/add";
    }

    /**
     * 添加用户（后端数据验证）
     */
    // @PostMapping("/add")
    public String add(@Valid StorageRecord storageRecord, BindingResult bindingResult, HttpSession session, @RequestParam(value =
            "attachs", required = false) MultipartFile[] attachs) {
        // 后端数据校验
        if (bindingResult.hasErrors()) {
            logger.debug("/storageRecord/add 添加用户验证失败");
            return "storageRecord/add";
        }

        // 从Session中获取当前登录用户
        StorageRecord loginUser = (StorageRecord) session.getAttribute(Constants.USER_SESSION);
        // 设置现在新添加的用户是由哪个账号创建的（填充数据库中createdUserId字段）
        storageRecord.setCreatedUserId(loginUser.getId());

        // 将数据保存到数据库
        boolean flag = recordService.add(storageRecord);
        logger.debug("/storageRecord/add " + flag + "\n" + storageRecord.toString());
        // 添加功能完成，跳转到列表页面
        return "redirect:/storageRecord/list"; // 使用重定向（让浏览器重新发起请求）
    }
}